import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Select, Input, message, Alert } from 'antd';
import ConfigTable from '../../../../components/configTable';
import services from '../../../../../../services/api';
import { cloneDeep } from 'lodash';

let oldThirdInterfaceList = [];

const DataSourceOrder = forwardRef((props, ref) => {
  const { value, interfaceType, onThirdInterfaceChange } = props;
  const [supplierIdOptions, setSupplierIdOptions] = useState([]);
  const [data, setData] = useState([]);

  useEffect(() => {
    getSupplierList();
  }, []);

  useEffect(() => {
    // // 将后端数据转为前使用的数据
    value.thirdInterfaceList && getTransferUseData(value.thirdInterfaceList);
  }, [value.thirdInterfaceList]);

  useEffect(() => {
    const getData = async () => {
      const oldList = oldThirdInterfaceList;
      const newList = data.filter((item) => item.id);
      const tempList = cloneDeep(value.thirdList);
      const newLen = newList.length;
      const oldLen = oldList.length;
      // 增加
      if (newLen > oldLen) {
        const oldIds = oldList.map((item) => item.id);
        await Promise.all(
          newList.map(async (item) => {
            if (!oldIds.includes(item.id)) {
              const { data } = await services.dataSource.detail(item.id);
              tempList.push(data);
            }
          })
        );
        onThirdInterfaceChange(tempList, undefined);
      }
      // 删除
      else if (oldLen > newLen) {
        const newIds = newList.map((item) => item.id);
        oldList.forEach((item) => {
          if (!newIds.includes(item.id)) {
            const index = tempList.map((item) => item.id).indexOf(item.id);
            tempList.splice(index, 1);
            onThirdInterfaceChange(tempList, [item.id]);
          }
        });
      }
      // 改变
      else {
        newList.forEach(async (item, index) => {
          if (item.id !== oldList[index].id) {
            const { data } = await services.dataSource.detail(item.id);
            const index1 = tempList.findIndex((item) => item.id === oldList[index].id);
            tempList.splice(index1, 1, data);
            onThirdInterfaceChange(tempList, [item.id, oldList[index].id]);
          }
        });
      }
      oldThirdInterfaceList = newList;
    };
    getData();
  }, [data]);

  const getTransferUseData = async (data) => {
    const tempThirdInterfaceList = data.map(({ id, supplierId, orderOrWeight }) => ({
      id,
      supplierId,
      orderOrWeight,
    }));
    for (const item of tempThirdInterfaceList) {
      const { data } = await services.dataSource.dataSourceListBySupplier(item.supplierId);
      item['interfaceList'] = data;
    }
    setData(tempThirdInterfaceList);
  };

  useImperativeHandle(ref, () => ({
    getData: () => {
      if (!data || data.length < 2) {
        throw '请至少添加两条数据源';
      }
      data.forEach((item, index) => {
        if (!item.id) {
          throw '数据源接口不能为空';
        }
        if (interfaceType) {
          item['orderOrWeight'] = index + 1;
        }
        if (!interfaceType && !item.orderOrWeight) {
          throw '请配置权重';
        }
      });
      return data;
    },
  }));

  // 根据id查找name
  const getNameById = (id, data) => data.find((item) => item.id === id).name;

  // 获取供应商
  const getSupplierList = async () => {
    const { data } = await services.dataSource.supplierList();
    setSupplierIdOptions(data);
  };
  // 根据选择供应商获取接口
  const handleSupplierChange = async (supplierId, index) => {
    const { code, data: interfaceList, msg } = await services.dataSource.dataSourceListBySupplier(supplierId);
    if (code) return message.warning(msg);
    const temp = data.slice();
    const tempObj = {
      supplierId,
      supplierName: getNameById(supplierId, supplierIdOptions),
      id: undefined,
      interfaceList,
    };
    temp[index] = { ...temp[index], ...tempObj };
    setData(temp);
  };

  const handleInterfaceChange = (id, { interfaceList }, index, oldId) => {
    const temp = data.slice();
    const tempObj = {
      id,
      name: getNameById(id, interfaceList),
    };
    temp[index] = { ...temp[index], ...tempObj };
    setData(temp);
  };

  const hanleVisibleChange = (value, { supplierId, interfaceList }, index) => {
    const temp = data.slice();
    if (value && supplierId) {
      const interfaceIdList = data.map((item) => item.id);
      const tempList = interfaceList.map((item) => {
        item.disabled = false;
        if (interfaceIdList.includes(item.id)) {
          item.disabled = true;
        }
        return item;
      });
      temp[index].interfaceList = tempList;
      setData(temp);
    }
  };

  const handleChange = (value, index) => {
    const temp = data.slice();
    temp[index].orderOrWeight = value;
    setData(temp);
  };

  const beforeDeleteMethod = () => {
    if (data.length <= 2) {
      return message.warning('至少保留两个数据源！');
    }
  };

  const cusColumns = [
    {
      title: interfaceType ? '调用顺序' : '调用权重',
      dataIndex: 'orderOrWeight',
      render: (text, _, index) =>
        interfaceType ? (
          <>{index + 1}</>
        ) : (
          <Input value={text} placeholder='请输入调用权重' onChange={(e) => handleChange(e.target.value, index)} />
        ),
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierId',
      render: (text, record, index) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleSupplierChange(value, index)}>
          {supplierIdOptions.map((item) => (
            <Select.Option value={item.id} key={item.id}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '数据源接口名',
      dataIndex: 'id',
      render: (text, record, index) => (
        <Select
          value={text}
          placeholder='请选择'
          onChange={(value) => handleInterfaceChange(value, record, index)}
          onDropdownVisibleChange={(value) => hanleVisibleChange(value, record, index)}
        >
          {record.interfaceList &&
            record.interfaceList.map((item, index) => (
              <Select.Option value={item.id} key={index} disabled={item.disabled}>
                {item.name}
              </Select.Option>
            ))}
        </Select>
      ),
    },
  ];

  return (
    <>
      <ConfigTable
        data={data}
        onChange={setData}
        cusColumns={cusColumns}
        defaultData={{}}
        isOrder={false}
        beforeDeleteMethod={beforeDeleteMethod}
      />
      <Alert
        message={
          '请求中的所有参数，包括Path中的动态参数，Header参数，Query参数，Body参数（通过Form表单传输的参数），参数名称保证唯一。'
        }
        type='info'
        style={{ marginTop: '20px' }}
      />
    </>
  );
});
export default DataSourceOrder;
